import React, { useMemo, useState } from 'react';
import { View, StyleSheet, Switch } from 'react-native';
import {
  Layout,
  UI,
  useThemeColors,
  useClipboard,
  ClipboardService,
  ToastService,
} from '@gaozh1024/rn-toolkit';

const ClipboardTestScreen: React.FC = () => {
  const colors = useThemeColors();
  const styles = useMemo(
    () =>
      StyleSheet.create({
        section: { marginBottom: 16 },
        row: { flexDirection: 'row', alignItems: 'center', flexWrap: 'wrap', gap: 12 },
        col: { gap: 12 },
        card: { borderRadius: 12, borderWidth: 1, borderColor: colors.border },
        bordered: { borderWidth: 1, borderColor: colors.border, borderRadius: 8, padding: 12 },
      }),
    [colors],
  );

  // 全局选项：是否显示提示 + 提示文案
  const [showToast, setShowToast] = useState<boolean>(true);
  const [toastMessage, setToastMessage] = useState<string>('复制成功');

  // Hook 状态与方法
  const {
    clipboardText,
    copyToClipboard,
    getFromClipboard,
    copyObject,
    getObject,
    clearClipboard,
  } = useClipboard();

  // Hook 页面状态
  const [hookText, setHookText] = useState<string>('Hello World');
  const [hookObjectJSON, setHookObjectJSON] = useState<string>('{ "foo": "bar", "count": 1 }');
  const [hookReadText, setHookReadText] = useState<string>('');
  const [hookObjectRead, setHookObjectRead] = useState<any | null>(null);

  // Service 页面状态
  const [svcText, setSvcText] = useState<string>('Service 文本内容');
  const [svcObjectJSON, setSvcObjectJSON] = useState<string>('{"a":1,"b":2}');
  const [svcReadText, setSvcReadText] = useState<string>('');
  const [svcObjectRead, setSvcObjectRead] = useState<any | null>(null);
  const [svcURL, setSvcURL] = useState<string>('https://example.com');

  // Hook：复制文本
  const onHookCopyText = async () => {
    const ok = await copyToClipboard(hookText, { showToast, toastMessage });
    ToastService.show({ message: ok ? 'Hook: 复制文本成功' : 'Hook: 复制文本失败' });
  };
  // Hook：读取文本
  const onHookReadText = async () => {
    const txt = await getFromClipboard();
    setHookReadText(txt || '');
    ToastService.show({ message: `Hook: 读取文本 ${txt ? '成功' : '为空'}` });
  };
  // Hook：清空
  const onHookClear = async () => {
    const ok = await clearClipboard();
    ToastService.show({ message: ok ? 'Hook: 清空成功' : 'Hook: 清空失败' });
    setHookReadText('');
    setHookObjectRead(null);
  };
  // Hook：复制对象（JSON）
  const onHookCopyObject = async () => {
    try {
      const obj = JSON.parse(hookObjectJSON);
      const ok = await copyObject(obj, { showToast, toastMessage });
      ToastService.show({ message: ok ? 'Hook: 复制对象成功' : 'Hook: 复制对象失败' });
    } catch (e) {
      ToastService.show({ message: 'Hook: JSON 解析失败' });
    }
  };
  // Hook：读取对象
  const onHookGetObject = async () => {
    const obj = await getObject<any>();
    setHookObjectRead(obj);
    ToastService.show({ message: obj ? 'Hook: 读取对象成功' : 'Hook: 读取对象为空或失败' });
  };

  // Service：复制文本
  const onSvcCopyText = async () => {
    const ok = await ClipboardService.copyToClipboard(svcText, { showToast, toastMessage });
    ToastService.show({ message: ok ? 'Service: 复制文本成功' : 'Service: 复制文本失败' });
  };
  // Service：读取文本
  const onSvcReadText = async () => {
    const txt = await ClipboardService.getFromClipboard();
    setSvcReadText(txt || '');
    ToastService.show({ message: `Service: 读取文本 ${txt ? '成功' : '为空'}` });
  };
  // Service：清空
  const onSvcClear = async () => {
    const ok = await ClipboardService.clearClipboard();
    ToastService.show({ message: ok ? 'Service: 清空成功' : 'Service: 清空失败' });
    setSvcReadText('');
    setSvcObjectRead(null);
  };
  // Service：复制对象（JSON）
  const onSvcCopyObject = async () => {
    try {
      const obj = JSON.parse(svcObjectJSON);
      const ok = await ClipboardService.copyObjectToClipboard(obj, { showToast, toastMessage });
      ToastService.show({ message: ok ? 'Service: 复制对象成功' : 'Service: 复制对象失败' });
    } catch (e) {
      ToastService.show({ message: 'Service: JSON 解析失败' });
    }
  };
  // Service：读取对象
  const onSvcGetObject = async () => {
    const obj = await ClipboardService.getObjectFromClipboard<any>();
    setSvcObjectRead(obj);
    ToastService.show({ message: obj ? 'Service: 读取对象成功' : 'Service: 读取对象为空或失败' });
  };
  // Service：复制 URL（直接把 URL 写入剪贴板）
  const onSvcCopyURL = async () => {
    const ok = await ClipboardService.copyToClipboard(svcURL, { showToast, toastMessage });
    ToastService.show({ message: ok ? 'Service: 复制 URL 成功' : 'Service: 复制 URL 失败' });
  };
  // Service：判断剪贴板是否是 URL
  const onSvcCheckURL = async () => {
    const is = await ClipboardService.isClipboardURL();
    ToastService.show({ message: is ? 'Service: 剪贴板内容是 URL' : 'Service: 剪贴板内容不是 URL' });
  };
  // Service：读取 URL
  const onSvcGetURL = async () => {
    const url = await ClipboardService.getURLFromClipboard();
    ToastService.show({ message: url ? `Service: 读取到 URL: ${url}` : 'Service: 未读取到 URL' });
  };

  return (
    <Layout.Page
      headerShown
      headerProps={{ title: 'Clipboard 测试', backVisible: true }}
      padding={16}
      scrollable
      testID="ClipboardTestScreen"
    >
      {/* 全局选项 */}
      <View style={styles.section}>
        <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
          <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>全局选项</UI.Text>
          <View style={styles.row}>
            <UI.Text color="text">显示提示</UI.Text>
            <Switch
              value={showToast}
              onValueChange={setShowToast}
              testID="clipboard-switch-toast"
            />
            <UI.Input
              value={toastMessage}
              onChangeText={setToastMessage}
              placeholder="自定义提示文案"
              style={{ flex: 1 }}
              testID="clipboard-input-toast-msg"
            />
          </View>
        </Layout.Card>
      </View>

      {/* Hook：复制/读取/清空（文本与对象） */}
      <View style={styles.section}>
        <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
          <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>Hook 测试</UI.Text>

          {/* 文本 */}
          <UI.Text color="text" style={{ marginTop: 4 }}>文本</UI.Text>
          <View style={styles.row}>
            <UI.Input
              value={hookText}
              onChangeText={setHookText}
              placeholder="要复制的文本（Hook）"
              style={{ flex: 1 }}
              testID="clipboard-hook-input-text"
            />
          </View>
          <View style={[styles.row, { marginTop: 8 }]}>
            <UI.Button title="复制文本（Hook）" onPress={onHookCopyText} testID="clipboard-hook-btn-copy-text" />
            <UI.Button title="读取文本（Hook）" variant="outline" onPress={onHookReadText} testID="clipboard-hook-btn-read-text" />
            <UI.Button title="清空（Hook）" variant="outline" onPress={onHookClear} testID="clipboard-hook-btn-clear" />
          </View>
          <View style={[styles.bordered, { marginTop: 12 }]}>
            <UI.Text variant="caption" color="subtext" mb={8}>clipboardText（来自 hook 状态）：</UI.Text>
            <UI.Text variant="body2" color="text" testID="clipboard-hook-text-state">{clipboardText}</UI.Text>
            <UI.Text variant="caption" color="subtext" mt={12} mb={8}>最近读取文本（Hook）：</UI.Text>
            <UI.Text variant="body2" color="text" testID="clipboard-hook-read-text">{hookReadText || '（空）'}</UI.Text>
          </View>

          {/* 对象 */}
          <UI.Text color="text" style={{ marginTop: 16 }}>对象（JSON）</UI.Text>
          <View style={styles.row}>
            <UI.Input
              value={hookObjectJSON}
              onChangeText={setHookObjectJSON}
              placeholder='示例：{ "foo": "bar", "count": 1 }'
              style={{ flex: 1 }}
              testID="clipboard-hook-input-json"
            />
          </View>
          <View style={[styles.row, { marginTop: 8 }]}>
            <UI.Button title="复制对象（Hook）" onPress={onHookCopyObject} testID="clipboard-hook-btn-copy-object" />
            <UI.Button title="读取对象（Hook）" variant="outline" onPress={onHookGetObject} testID="clipboard-hook-btn-read-object" />
          </View>
          <View style={[styles.bordered, { marginTop: 12 }]}>
            <UI.Text variant="caption" color="subtext" mb={8}>最近读取对象（Hook）：</UI.Text>
            <UI.Text variant="body2" color="text" testID="clipboard-hook-read-object">
              {hookObjectRead ? JSON.stringify(hookObjectRead) : '（空）'}
            </UI.Text>
          </View>
        </Layout.Card>
      </View>

      {/* Service：复制/读取/清空（文本、对象、URL） */}
      <View style={styles.section}>
        <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
          <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>Service 测试</UI.Text>

          {/* 文本 */}
          <UI.Text color="text" style={{ marginTop: 4 }}>文本</UI.Text>
          <View style={styles.row}>
            <UI.Input
              value={svcText}
              onChangeText={setSvcText}
              placeholder="要复制的文本（Service）"
              style={{ flex: 1 }}
              testID="clipboard-svc-input-text"
            />
          </View>
          <View style={[styles.row, { marginTop: 8 }]}>
            <UI.Button title="复制文本（Service）" onPress={onSvcCopyText} testID="clipboard-svc-btn-copy-text" />
            <UI.Button title="读取文本（Service）" variant="outline" onPress={onSvcReadText} testID="clipboard-svc-btn-read-text" />
            <UI.Button title="清空（Service）" variant="outline" onPress={onSvcClear} testID="clipboard-svc-btn-clear" />
          </View>
          <View style={[styles.bordered, { marginTop: 12 }]}>
            <UI.Text variant="caption" color="subtext" mb={8}>最近读取文本（Service）：</UI.Text>
            <UI.Text variant="body2" color="text" testID="clipboard-svc-read-text">{svcReadText || '（空）'}</UI.Text>
          </View>

          {/* 对象 */}
          <UI.Text color="text" style={{ marginTop: 16 }}>对象（JSON）</UI.Text>
          <View style={styles.row}>
            <UI.Input
              value={svcObjectJSON}
              onChangeText={setSvcObjectJSON}
              placeholder='示例：{"a":1,"b":2}'
              style={{ flex: 1 }}
              testID="clipboard-svc-input-json"
            />
          </View>
          <View style={[styles.row, { marginTop: 8 }]}>
            <UI.Button title="复制对象（Service）" onPress={onSvcCopyObject} testID="clipboard-svc-btn-copy-object" />
            <UI.Button title="读取对象（Service）" variant="outline" onPress={onSvcGetObject} testID="clipboard-svc-btn-read-object" />
          </View>
          <View style={[styles.bordered, { marginTop: 12 }]}>
            <UI.Text variant="caption" color="subtext" mb={8}>最近读取对象（Service）：</UI.Text>
            <UI.Text variant="body2" color="text" testID="clipboard-svc-read-object">
              {svcObjectRead ? JSON.stringify(svcObjectRead) : '（空）'}
            </UI.Text>
          </View>

          {/* URL */}
          <UI.Text color="text" style={{ marginTop: 16 }}>URL</UI.Text>
          <View style={styles.row}>
            <UI.Input
              value={svcURL}
              onChangeText={setSvcURL}
              placeholder="要复制的 URL（Service）"
              style={{ flex: 1 }}
              testID="clipboard-svc-input-url"
            />
          </View>
          <View style={[styles.row, { marginTop: 8 }]}>
            <UI.Button title="复制 URL（Service）" onPress={onSvcCopyURL} testID="clipboard-svc-btn-copy-url" />
            <UI.Button title="检查是否 URL（Service）" variant="outline" onPress={onSvcCheckURL} testID="clipboard-svc-btn-check-url" />
            <UI.Button title="读取 URL（Service）" variant="outline" onPress={onSvcGetURL} testID="clipboard-svc-btn-read-url" />
          </View>
        </Layout.Card>
      </View>
    </Layout.Page>
  );
};

export default ClipboardTestScreen;